package com.financial.service.yspay.service.impl;

import com.financial.service.yspay.dto.FinancialYsPayDTO;
import com.financial.service.yspay.service.FinancialYsPayVerifyJsonSignService;
import com.financial.service.yspay.utils.SignUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Map;

/**
 * @Author: WANGNING
 * @Email wyn20140226@aliyun.com
 * @Date: 2019/6/4 18:28
 * @Des API验证签名工具，把签名值，请求字符编码，返回结果(json body)传递过来进行验证签名 公钥验证签名
 * *   用于验证银盛同步响应回来的参数
 */
@Service
public class FinancialYsPayVerifyJsonSignServiceImpl implements FinancialYsPayVerifyJsonSignService {

    @Override
    public boolean verifyJsonSign(String sign, String responseBody, String charset, FinancialYsPayDTO ysPayDTO) {
//		ServletContext servletContext = request.getServletContext();
        InputStream publicCertFileInputStream = null;//servletContext.getResourceAsStream(ysepayConfig.PATH_YSEPAY_PUBLIC_CERT);
        //YsPayDTO ysPayDTO=ysBusinessPramService.ysBusinessPram();

        boolean isSign = false;
        try {
            publicCertFileInputStream = new ClassPathResource(ysPayDTO.getPATH_YSEPAY_PUBLIC_CERT()).getInputStream();//加载本地的证书进行https加密传输
            isSign = SignUtils.rsaCheckContent1(publicCertFileInputStream, responseBody, sign, charset, ysPayDTO);
        } catch (Exception e) {
            throw new RuntimeException("验证签名失败，请检查银盛公钥证书文件是否存在");
        }
        return isSign;
    }

    /**
     * @Author: WANGNING
     * @Email wyn20140226@aliyun.com
     * @Date: 2019/6/4 18:28
     * @Des API验证签名工具，把签名值，请求字符编码，返回结果(json body)传递过来进行验证签名 公钥验证签名
     * *   用于验证银盛异步响应回来的参数
     */
    @Override
    public boolean verifySign(Map<String, String> params, FinancialYsPayDTO ysPayDTO) {

        InputStream publicCertFileInputStream = null;//servletContext.getResourceAsStream(YspayConfig.PATH_YSEPAY_PUBLIC_CERT);

        String sign = "";
        if (params.get("sign") != null) {
            sign = params.get("sign");
            params.remove("sign");
            SignUtils.getSContent(params);
        }
        boolean isSign = false;
        try {
            publicCertFileInputStream = new ClassPathResource(ysPayDTO.getPATH_YSEPAY_PUBLIC_CERT()).getInputStream();//加载本地的证书进行https加密传输
            isSign = SignUtils.rsaCheckContent(publicCertFileInputStream, params, sign, "utf-8", ysPayDTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("验证签名失败，请检查银盛公钥证书文件是否存在");
        }

        return isSign;
    }

}
